/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.module.ai.biz.service;

import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.store.embedding.EmbeddingStore;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/** 智能助手初始化 */
@Configuration
@RequiredArgsConstructor
public class AssistantInit {
  private final ChatLanguageModel chatLanguageModel;

  private final StreamingChatLanguageModel streamingChatModel;

  /**
   * 初始化会话
   *
   * @param embeddingStore 向量数据库
   * @return formatter
   */
  @Bean
  public Assistant init(EmbeddingStore<TextSegment> embeddingStore) {
    return AiServices.builder(Assistant.class)
        // 配置会话记忆存储， 通过memoryId进行会话隔离
        .chatMemoryProvider(memoryId -> MessageWindowChatMemory.withMaxMessages(10))
        // 配置向量数据库
        .contentRetriever(EmbeddingStoreContentRetriever.from(embeddingStore))
        .systemMessageProvider(chatMemoryId -> "你是一名专业程序员，回答的时候需要更精确") // 系统提示词
        // 关闭联网搜索能力  new WebSearchTool(engine)
        // 结构化输入（自定义函数工具）
        .tools(new HighLevelCalculator())
        .chatLanguageModel(chatLanguageModel)
        .streamingChatLanguageModel(streamingChatModel)
        .build();
  }
}
